<template>
	<view>
		<!-- <u-navbar :is-back="true" :is-fixed="true" title="账号信息"></u-navbar> -->
		<free-list-item title="我的头像" :showRight="false" :showLeftIcon="false"
			@click="userInfo && userInfo.parentId === null ? updates('navatar') : null">
			<u-image slot="right" :src="getFullImageUrl(ifdUser.avatar)" border-radius="100rpx"
				style="width: 60px; height: 60px; margin-right: 10px;" @error="handleImageError"></u-image>
		</free-list-item>
		<free-list-item title="名字" :showRight="false" :showRightIcons="false" :showLeftIcon="false">
			<text slot="right" class="font-14 text-muted">{{ifdUser.username}}</text>
		</free-list-item>
		<free-list-item title="绑定手机号" :showRight="false" :showLeftIcon="false"
			@click="userInfo && userInfo.parentId === null ? updates('bindPhone') : null">
			<text slot="right" class="font-14 text-muted ursrRight">{{ifdUser.phone}}</text>
		</free-list-item>

		<free-list-item title="登录密码" :showRight="false" :showLeftIcon="false"
			@click=" userInfo && userInfo.parentId === null ? updates('Password') : null">
			<text slot="right" class="font-14 text-muted ursrRight">{{maskedPassword}}</text>
		</free-list-item>
		<!-- 修改名字|修改微信号 弹框-->
		<free-confirm ref="confirm" :title="confirmTitle">
			<view class="pl-3">
				<u-form :model="form" ref="uForm">
					<u-form-item required label-width="120" label="原密码" prop="oldPassword">
						<u-input class="mr-3" :password-icon="true" type="password" placeholder="请输入原密码"
							v-model="form.oldPassword" input-align="right" />
					</u-form-item>
					<u-form-item required label="新密码" label-width="120" prop="newPassword">
						<u-input class="mr-3" :password-icon="true" type="password" placeholder="请输入新密码"
							v-model="form.newPassword" input-align="right" />
					</u-form-item>
					<u-form-item required label="确认新密码" label-width="180" prop="confirmPassword">
						<u-input class="mr-3" :password-icon="true" type="password" placeholder="请再次输入密码"
							v-model="form.confirmPassword" input-align="right" />
					</u-form-item>
				</u-form>
				<view class="font-12 mt-1" style="color: red;">由英文、数字、特殊字符中的至少2种组成，不少于6位</view>
			</view>
		</free-confirm>
		<!-- 修改手机号码 弹框-->
		<free-confirm ref="confirmShow" :title="confirmPhomTitle">
			<view class="pl-3">
				<u-form :model="form">
					<u-form-item required label="手机号码" label-width="180" prop="phone">
						<u-input class="mr-3 " maxlength="11" placeholder="请输入所绑定的手机号" v-model="code.phone"
							input-align="right" />
					</u-form-item>
					<u-form-item required label="验证码" label-width="180" prop="captcha">
						<u-input class="mr-3 " placeholder="请输入验证码" v-model="code.captcha" input-align="right" />
						<u-button size="mini" slot="right" type="warning" @click="getCode">{{codeText}}</u-button>
					</u-form-item>
				</u-form>
				<u-toast ref="uToast"></u-toast>
				<u-verification-code :seconds="seconds" @end="end" @start="start" ref="uCode"
					@change="codeChange"></u-verification-code>
			</view>
		</free-confirm>
	</view>
</template>

<script>
	import $H from '@/common/free-lib/request.js';
	import {
		getImageUrl
	} from '@/common/free-lib/util.js';
	import freeListItem from "@/components/free-ui/free-list-item.vue";
	import freeAvater from "@/components/free-ui/free-avater.vue";
	import freeDivider from "@/components/free-ui/free-divider.vue";
	import freeConfirm from "@/components/free-ui/free-confirm.vue";
	export default {
		components: {
			freeListItem,
			freeAvater,
			freeDivider,
			freeConfirm
		},
		data() {
			return {
				codeText: '',
				confirmType: "",
				seconds: 60,
				form: {
					confirmPassword: "",
					newPassword: "",
					oldPassword: "",
				},
				ifdUser: '',
				avatar: '',
				labelStyle: {
					paddingLeft: '13px',
					width: '130px'
				},
				code: {
					phone: '',
					captcha: ''
				},
				userInfo: null,
				rules: {
					oldPassword: [{
							required: true,
							message: '原密码不能为空',
							trigger: ['change', 'blur'],
						},
						{
						    validator: (rule, value, callback) => {
						        // 正则表达式，要求密码包含英文、数字、特殊字符中的至少2种组成，不少于6位
						        const reg = /^(?=.*[a-zA-Z])(?=.*\d|.*[\W_])[A-Za-z\d\W_]{6,}$/;
						        if (!reg.test(value)) {
						            callback(new Error('密码必须包含英文、数字、特殊字符中的至少二种，且长度不少于6位'));
						        } else {
						            callback();
						        }
						    },
						    trigger: ['change', 'blur'],
						}
					],
					newPassword: [{
							required: true,
							message: '新密码不能为空',
							trigger: ['change', 'blur'],
						},
						{
						    validator: (rule, value, callback) => {
						        // 正则表达式，要求密码包含英文、数字、特殊字符中的至少2种组成，不少于6位
						        const reg = /^(?=.*[a-zA-Z])(?=.*\d|.*[\W_])[A-Za-z\d\W_]{6,}$/;
						        if (!reg.test(value)) {
						            callback(new Error('密码必须包含英文、数字、特殊字符中的至少二种，且长度不少于6位'));
						        } else {
						            callback();
						        }
						    },
						    trigger: ['change', 'blur'],
						}
					],
					confirmPassword: [{
							required: true,
							message: '确认新密码不能为空',
							trigger: ['change', 'blur'],
						},
						{
						    validator: (rule, value, callback) => {
						        // 正则表达式，要求密码包含英文、数字、特殊字符中的至少2种组成，不少于6位
						        const reg = /^(?=.*[a-zA-Z])(?=.*\d|.*[\W_])[A-Za-z\d\W_]{6,}$/;
						        if (!reg.test(value)) {
						            callback(new Error('密码必须包含英文、数字、特殊字符中的至少二种，且长度不少于6位'));
						        } else {
						            callback();
						        }
						    },
						    trigger: ['change', 'blur'],
						}
					],
				},

			}
		},
		computed: {
			confirmTitle() {
				return this.confirmType == 'username' ? '修改密码' : '修改密码'
			},
			confirmPhomTitle() {
				return this.confirmType == 'username' ? '绑定手机号' : '绑定手机号'
			},
			placeholder() {
				return this.confirmType == 'username' ? '输入账号' : '输入名称'
			},
			maskedPassword() {
				// 如果 this.ifdUser 不存在或者 username 为空，则返回空字符串
				if (!this.ifdUser || !this.ifdUser.username) {
					return '';
				}
				// 否则将密码替换为星号
				return this.ifdUser.username.replace(/./g, "******");
			},
		},

		onLoad(options) {
			const id = options.id;
			this.NewUser(id);
			const userInfo = uni.getStorageSync('userInfo');
			this.userInfo = userInfo
		},
		methods: {
			handleImageError() {
				uni.showToast({
					title: '图片格式不支持jpeg，请重新上传',
					icon: 'none',
					duration: 4000
				});

			},
			// 拼接图片方法
			getFullImageUrl(imagePath) {
				return getImageUrl(imagePath);
			},
			codeChange(text) {
				this.codeText = text;
			},
			validatePhoneNumber(phoneNumber) {
				var regex = /^[0-9]{9}$/;
				return regex.test(phoneNumber);
			},

			getCode() {
				if (this.getCodeisWaiting) {
					return;
				}
				// 验证手机号码是否为空
				if (!this.code.phone) {
					uni.showToast({
						title: "请输入手机号码",
						icon: 'none'
					});
					return;
				}
				// 隐藏键盘
				uni.hideKeyboard();
				this.getCodeText = "发送中...";
				this.getCodeisWaiting = true;
				let o = {
					phone: this.code.phone
				};

				// 发送请求获取验证码
				$H.post('/brand/user/agriculture/editePhoneSendSms', o, {
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
						}
					})
					.then(res => {
						if (!res.success || res.code != 200) {
							uni.showToast({
								title: res.message || '获取验证码失败',
								icon: 'error'
							});
							return;
						}
						if (this.$refs.uCode.canGetCode) {
							if (!this.validatePhoneNumber(this.code.phone)) {
								uni.showToast({
									title: "手机号码格式错误",
									icon: "error"
								});
								return;
							}
							uni.showLoading({
								title: '正在获取验证码'
							});
							setTimeout(() => {
								uni.hideLoading();
								this.$refs.uCode.start();
							}, 2000);
						} else {
							this.$u.toast('倒计时结束后再发送');
						}
					})
					.catch(error => {
						uni.showToast({
							title: "网络错误，请稍后再试",
							icon: 'none'
						});
					});
			},
			end() {
				this.$u.toast('倒计时结束');
				this.getCodeisWaiting = false;
				this.codeText = '重新获取';
			},
			start() {
				this.$u.toast('倒计时开始');
			},
			editePhone(id) {
				let o = {
					...this.code,
					id: this.id
				};
				$H.post('/brand/user/agriculture/editePhone', o, {
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
						}
					})
					.then(res => {
						if (res.code === 200) {
							uni.showToast({
								title: res.message,
								icon: 'none',
							});
							this.phoneData()
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
							});
						}
					})
					.catch(error => {
						uni.showToast({
							title: "网络错误，请稍后再试",
							icon: 'none'
						});
					});
			},
			phoneData() {
				// 清空表单数据
				this.code.phone = '';
				this.code.captcha = '';
			},
			/**end  验证码**/


			/**start  修改密码**/
			changePassword(id) {

				let o = {
					...this.form,
					id: this.id
				};
				$H.post('/brand/user/agriculture/editPassword', o, {
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
						}
					})
					.then(res => {
						if (res.code === 200) {
							uni.showToast({
								title: res.message,
								icon: 'none',
							});
							// 关闭弹框并清空数据
							this.clearData();
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
							});
						}
					})
					.catch(error => {
						uni.showToast({
							title: "网络错误，请稍后再试",
							icon: 'none'
						});
					});

			},
			clearData() {
				// 清空表单数据
				this.form.confirmPassword = '';
				this.form.newPassword = '';
				this.form.oldPassword = '';
			},
			/** end 修改密码**/

			updates(key) {
				const this_ = this;
				switch (key) {
					case 'navatar':
						uni.chooseImage({
							count: 1,
							sizeType: ['compressed'],
							success: (res) => {
								// 上传
								this_.avatars(res.tempFilePaths[0]);
							}
						})
						break;
					case 'bindPhone':
						// 处理绑定手机号码逻辑，弹起弹框
						this_.confirmType = 'bindPhone';
						this_.$refs.confirmShow.show((close) => {
							this_.editePhone();

							close();
						});
						break;
					case 'Password':
						this_.$refs.confirm.show(function(close) {

							this_.changePassword();

							close();
						});
					default:
						break;
				}
			},
			avatars(filePath) {
				$H.upload('/sys/common/upload', {
					filePath: filePath
				}, {}).then((avatar) => {
					if (avatar && avatar.message) {
						$H.post('/brand/user/agriculture/editAvatar', {
							avatar: avatar.message // 将 avatar 传递给 editAvatar 方法
						}, {
							header: {
								'Content-Type': 'application/x-www-form-urlencoded'
							}
						}).then((res) => {
							if (res.code === 200) {
								uni.showToast({
									title: res.message,
									icon: 'none',
								});
								this.NewUser(this.id);
							} else {
								uni.showToast({
									title: res.message,
									icon: 'none',
								});
							}
							// 在这里处理 editAvatar 方法返回的数据
						}).catch((error) => {
							console.error('编辑头像失败', error);
							uni.showToast({
								title: '编辑头像失败',
								icon: 'none'
							});
						});
					} else {
						uni.showToast({
							title: '上传失败,图片限制不能超过4MB',
							icon: 'none',
							duration: 4000
						});
					}
				}).catch((error) => {
					console.error('上传失败', error);
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					});
				});
			},

			openCode() {
				uni.navigateTo({
					url: '/pages/my/code/code'
				})
			},
			NewUser(id) {
				$H.get('/brand/user/queryById', {
					id: id
				}, {}).then(res => {
					this.ifdUser = res.result
					this.id = res.result.id
				}).catch(error => {
					uni.showToast({
						title: "网络错误，请稍后再试",
						icon: 'none'
					});
				});
			},
		}
	}
</script>

<style>
</style>